package com.html2rss.core;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;

import com.html2rss.core.exceptions.HtmlToRssException;

import javax.xml.xpath.*;

/**
 * User: VSlaykovskiy
 * Date: 13.04.2007
 * Time: 12:33:03
 */
public class DomHelper {
    public static Node findCommonParent(List<Node> nodes) {
        if (nodes == null) return null;
        if (nodes.size() == 1) return nodes.get(0).getParentNode();
        HashMap <Node, List <Node> > map = new HashMap<Node, List<Node>>();
        for (Node nod:nodes) {
            Node n = nod;
            while (n!=null) {
                if (!map.containsKey(n)) {
                    map.put(n, new ArrayList<Node>());
                }
                map.get(n).add(nod);
                if (map.get(n).size() == nodes.size()) {
                    return n;
                }
                n = n.getParentNode();
            }
        }
        return null; // todo
    }
    public static List <Node> findNodesByAttrValue(Node node, String attr, String value) {
        List<Node> result = null;
        try {
            result = new ArrayList<Node>();
            String expression = "//*[@"+attr+"='"+value+"']";
            result = getXPathNodeList(expression, node);

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static List <Node> getXPathNodeList(String expression, Node node) throws XPathExpressionException {
        NodeList nodes = (NodeList) XPathFactory.newInstance().newXPath().compile(expression).evaluate(node, XPathConstants.NODESET);
        List<Node> result = new ArrayList<Node>();
        for (int i=0; i<nodes.getLength(); i++) {
             result.add(nodes.item(i));
        }
        return result;
    }

    public static int getNodePosition (Node node) throws HtmlToRssException {
        Node parentNode = node.getParentNode();
        if (parentNode==null) return -1;
        int counter = 1;
        for (int i=0; i<parentNode.getChildNodes().getLength(); i++) {
            if (node == parentNode.getChildNodes().item(i)) {
                return counter;
            }
            if (node.getNodeName().equalsIgnoreCase(parentNode.getChildNodes().item(i).getNodeName())) {
                counter++;
            }
        }
        throw new HtmlToRssException("bad node");
    }
}
